#!/usr/bin/env python

import pod
from pod.grammar import *
from pod.std import *

from cStringIO import StringIO
import collections
import traceback

# get rid of later
from pod.macros.html.util import tag
            
class Parser(object):
    def __init__(self, ctx):
        self.ctx = ctx
        self.grammar = Grammar()
        
    def collectMacros(self, content):
        """
        Use parser to find all locations that macros occur.
        """
        macros = []
        for macro, s, e in self.grammar.findMacros(content):
            if len(macro) > 0: macros.append((macro[0], s, e))
        return macros
                    
    def parseString(self, doc):
        # first discover all transforms from parsing out the macros
        replace = {}
        for macro, s, e in self.collectMacros(doc):
            instance = getMacroInstance(self.ctx, macro)
            eb = ExecutionBlock(instance, macro.block, macro.delayed)
            transform = eb.execute(self.ctx)
            if transform != None: 
                # if there is a resulting transform, use it to replace
                # the macro with the transform
                value = str(transform)
                replace[s] = (e, value)
            else:
                # otherwise, just erase the macro
                replace[s] = (e, "")
            #endif
        #endfor
                
        # finally, rewrite document with macros expanded
        output = StringIO()
        i = 0
        while i < len(doc):
            if i in replace:
                # start at beginnning of block
                e, value = replace[i]
                
                # write contents of macro                
                if value != None: output.write(value)
                
                # skip to end of block
                i = e
            else:
                # otherwise, just write what's in the input
                output.write(doc[i])
                i += 1
        result = output.getvalue()
        output.close()
        return result
        
def parseFile(filename, env):
    with open(filename) as input:        
        parser = Parser(env)
        doc = "".join(input.readlines())
        return parser.parseString(doc)

if __name__ == "__main__":
    #env = {"scope":[], "log":open(sys.argv[1] + ".log", "w")}
    env = {"doctype": "all"}
    ctx = Context(env, [], [])
    try:
        print parseFile(sys.argv[1], ctx)
    except MacroNotFound as e:
        print "Could not find macro '%s'" % e.name
    except MacroIncorrectParameters as e:
        print "Error invoking macro: ", e.name
    except:
        #print "Unexpected error: ", sys.exc_info()
        traceback.print_exc(file=sys.stdout)
    #endtry
    